<?php

class MemberPositionController extends Controller {

	public $layout = '//layouts/column2';

	public function filters() {
		return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
		);
	}

	public function accessRules() {
		return array(
		array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'autoRun', 'deposit', 'positions'),
		//'users' => array('*'),
                'users' => array('@'),
		),
		array('allow', // allow authenticated user to perform 'create' and 'update' actions
                //'actions' => array('create', 'update'),
                'actions' => array('create'),
                'users' => array('@'),
		),
		array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete'),
                'users' => array('admin'),
                'expression' => '$user->isAdmin()'    
		),
		array('deny', // deny all users
                'users' => array('*'),
		),
		);
	}

	public function actionAutoRun() {
		$settings = Setting::model()->findAll();
		if (empty($settings)) {
			//Log message here.
			echo "Settings is not set";
			return;
		}
		$setting = $settings[0];
		if (!isset($setting)) {
			// Log message add here.
			echo "Setting is not set";
			return;
		}
		$curdate = date("Y-m-d");
		//$list= Yii::app()->db->createCommand('select * from member_position where substr(expire_date,1,10)>=:expire_date')->bindValue('expire_date',$expdate)->queryAll();
		$list = Yii::app()->db->createCommand("select * from member_position where substr(expire_date,1,10) >='" . $curdate . "'")->queryAll();

		foreach ($list as $position) {
			$sql = "select * from member_transaction_history where
					   substr(transaction_date,1,10) = '" . $curdate . "' and member_id=" . $position['member_id'] .
                    " and positions=" . $position["no_of_positions"];
			$tHistory = Yii::app()->db->createCommand($sql)->queryAll();
			/* if not empty means already process run for this postions */
			if (!empty($tHistory)) {
				// Log message add here.
				echo "Transaction on current date for that positons:" . $position["member_positions_id"] . " already exists";
				continue;
			}

			$sql = "select * from member_transaction_history where member_transaction_history_id = (
                    select max( member_transaction_history_id ) from member_transaction_history 
                    where member_id =" . $position['member_id'] . ")";

			$_lh = Yii::app()->db->createCommand($sql)->queryAll();
			$balance = 0;
			if (!empty($_lh)) {
				$_history = $_lh[0];
				if (!empty($_history)) {
					$balance = $_history['balance'];
				}
			}
			$mthModel = new MemberTransactionHistory();
			$mthModel->member_id = $position["member_id"];
			$mthModel->credit = $position["no_of_positions"] * $setting->positions_value * $setting->positions_outcome / 100;
			$mthModel->transaction_date = date("Y-m-d H:i:s");
			$mthModel->balance = $balance + $mthModel->credit;
			$mthModel->particulars = "Added profit amount for positions id :" . $position["member_positions_id"] . " and number of positions :" . $position["no_of_positions"];
			$mthModel->positions = $position["no_of_positions"];
			$mthModel->save();
			echo "Member transaction history added...";
		}
	}

	public function actionView($id) {
		$this->render('view', array(
            'model' => $this->loadModel($id),
		));
	}

	public function actionCreate() {
		$model = new MemberPosition;
		$balance = $this->getCurrentBalance(Yii::app()->user->id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$isOK = true;
		if (isset($_POST['MemberPosition'])) {
			$model->attributes = $_POST['MemberPosition'];
			$model->member_id = Yii::app()->user->id;
			$model->purchase_date = date("Y-m-d H:i:s");
			$model->expire_date = date('Y-m-d H:i:s', strtotime("+80 days"));

			$position = $model->no_of_positions;
			$rBalance = $position * 10;
			if ($balance < $rBalance) {
				Yii::app()->user->setFlash('error', "You do not have enough balance for purchasing ".$position
				." positions. Please go to the ". CHtml::link('Deposit Fund', array('memberPosition/deposit'))." to deposit required amount. !");
				$isOK = false;
			}
				
			/* Check first time position purchase. if first then first position commision will not add to referer */
			$list = MemberPosition::model()->findAll("member_id=:member", array("member" => Yii::app()->user->id));
			if (empty($list)){				
				$position = $position - 1;
			}
			if ($isOK && $model->save()) {
				/* deduc amount from his balance */
				$mthModel = new MemberTransactionHistory();
				$mthModel->member_id = Yii::app()->user->id;
				$mthModel->credit = 0;
				$mthModel->debit = $rBalance;
				$mthModel->transaction_date = date("Y-m-d H:i:s");
				$mthModel->balance = $balance - $rBalance;
				$mthModel->particulars = "Deduct for purchasing positions";
				$mthModel->positions = $model->no_of_positions;
				$mthModel->save();

				if(0 < $position){
					/* Add fist referer 10 %*/
					$member = Member::model()->findByPk(Yii::app()->user->id);					
					if(isset($member) && $member->upline_id){
						$cBalance = $this->getCurrentBalance($member->upline_id);
						$mthModel = new MemberTransactionHistory();
						$credit = $position * 10 * 10 / 100;
						$mthModel->member_id = $member->upline_id;
						$mthModel->credit = $credit;
						$mthModel->debit = 0;
						$mthModel->balance = $cBalance + $credit;
						$mthModel->transaction_date = date("Y-m-d H:i:s");
						$mthModel->particulars = "Add 10% referral amount";
						$mthModel->positions = 0;
						$mthModel->ref_id = $member->member_id;
						$mthModel->save();
					}
					/* Add second referer 5 %*/
					$frmember = Member::model()->findByPk($member->upline_id);
					if(isset($frmember) && $frmember->upline_id){
						$cBalance = $this->getCurrentBalance($frmember->upline_id);
						$mthModel = new MemberTransactionHistory();
						$credit = $position * 10 * 5 / 100;
						$mthModel->member_id = $frmember->upline_id;
						$mthModel->credit = $credit;
						$mthModel->debit = 0;
						$mthModel->balance = $cBalance + $credit;
						$mthModel->transaction_date = date("Y-m-d H:i:s");
						$mthModel->particulars = "Add 5% referral amount";
						$mthModel->positions = 0;
						$mthModel->ref_id = $member->member_id;;
						$mthModel->save();
					}
				}
				$this->redirect(array('view', 'id' => $model->member_positions_id));
			}
		}
		$pp = Member::model()->findByPK(Yii::app()->user->id)->memberAccounts;
		$this->render('create', array(
            'model' => $model,
            'balance' => $balance,
            'pp' => $pp
		));
	}

	function getCurrentBalance($id){
		$sql = "select * from member_transaction_history where member_transaction_history_id = (
                    select max( member_transaction_history_id ) from member_transaction_history 
                    where member_id =" . $id . ")";

		$_lh = Yii::app()->db->createCommand($sql)->queryAll();
		$balance = 0;
		if (!empty($_lh)) {
			$_history = $_lh[0];
			if (!empty($_history)) {
				$balance = $_history['balance'];
			}
		}
		return $balance;
	}

	public function actionUpdate($id) {
		$model = $this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['MemberPosition'])) {
			$model->attributes = $_POST['MemberPosition'];
			if ($model->save())
			$this->redirect(array('view', 'id' => $model->member_positions_id));
		}

		$this->render('update', array(
            'model' => $model,
		));
	}

	public function actionDelete($id) {
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if (!isset($_GET['ajax']))
		$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	public function actionIndex() {
		$dataProvider = new CActiveDataProvider('MemberPosition');
		$this->render('index', array(
            'dataProvider' => $dataProvider,
		));
	}

	public function actionDeposit() {
		$model = new DipositForm();
		if (isset($_POST['DipositForm'])) {
			$model->attributes = $_POST['DipositForm'];
			$model->validate();
		}
		$this->render('diposit', array('model' => $model));
	}

	public function actionAdmin() {
		$model = new MemberPosition('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['MemberPosition']))
		$model->attributes = $_GET['MemberPosition'];

		$this->render('admin', array('model' => $model));
	}
        
        public function actionPmStatus() {
            $this->render('_deposit_status', array('model1' => $_GET, 'model2' => $_POST));
        }
        
        public function actionPmPaymentStatus() {
            $this->render('_deposit_success', array('model1' => $_GET, 'model2' => $_POST));
        }
        
        public function actionPmNoPaymentStatus() {
            $this->render('_deposit_fail', array('model1' => $_GET, 'model2' => $_POST));
        }
        
        public function actionLrSuccess() {
            $model = array(
                'msg'=>"<p> We have received your payment. Your business is appreciated! </p>",
                'resget'=>$_GET,
                'respost'=>$_POST
            );
            
            $payment_processors_id = PaymentProcessor::model()->find("code=:code", array("code" => 'LR'))->payment_processors_id;
            $payment_processors_name = PaymentProcessor::model()->find("code=:code", array("code" => 'LR'))->name;
            //$aResponse = $oEgopay->getResponse($_POST);
            $balance = $this->getCurrentBalance(Yii::app()->user->id);
            
            $mthModel = new MemberTransactionHistory();
            $mthModel->member_id = Yii::app()->user->id;
            $mthModel->credit = $_REQUEST["lr_amnt"];
            $mthModel->debit = 0;
            $mthModel->transaction_date = date("Y-m-d H:i:s");
            $mthModel->balance = $balance + $_REQUEST["lr_amnt"];
            $mthModel->particulars = "Deposit from ". $payment_processors_name;
            $mthModel->payment_processors_id = $payment_processors_id;
            $mthModel->save();
            
            // get super admin here from db by member type 3  
            // ADD TO Withdraw
            $superid = Member::model()->find("member_type=:member_type", array('member_type'=>  LevelLookUp::SUPERADMIN))->member_id;
            $sbalance = $this->getCurrentBalance($superid);
            
            $smthModel = new MemberTransactionHistory();
            $smthModel->member_id = $superid;
            $smthModel->credit = $_REQUEST["lr_amnt"];
            $smthModel->debit = 0;
            $smthModel->transaction_date = date("Y-m-d H:i:s");
            $smthModel->balance = $sbalance + $_REQUEST["lr_amnt"];
            $smthModel->particulars = "Deposit by ref_id from ". $payment_processors_name;
            $smthModel->payment_processors_id = $payment_processors_id;
            $smthModel->ref_id = Yii::app()->user->id;
            $smthModel->save();
            
            $this->render('_deposit_success', array('model' => $model));
        }
        
        public function actionLrFail(){
            $model = array(
                'msg'=>"<p>Payment has failed. Please contact with site administrator</p>",
                'resget'=>$_GET,
                'respost'=>$_POST
            );
            $this->render('_deposit_fail', array('model' => $model));
        }
        
        public function actionLrStatus(){
            $this->render('_deposit_status', array('model1' => $_GET, 'model2' => $_POST));
        }
        
        public function actionEpSuccess(){            
            try {
            $oEgopay = new EgoPaySciCallback(array(
                'store_id' => '3MSB8NZP57J9',
                'store_password' => 'BH;qByO=hI^RZJ1FZ[UGM7aQ]HiXr:o9'
            ));
            $payment_processors_id = PaymentProcessor::model()->find("code=:code", array("code" => 'EP'))->payment_processors_id;
            $payment_processors_name = PaymentProcessor::model()->find("code=:code", array("code" => 'EP'))->name;
            $aResponse = $oEgopay->getResponse($_POST);
            $balance = $this->getCurrentBalance(Yii::app()->user->id);
            
            $mthModel = new MemberTransactionHistory();
            $mthModel->member_id = Yii::app()->user->id;
            $mthModel->credit = $aResponse['fAmount'];
            $mthModel->debit = 0;
            $mthModel->transaction_date = date("Y-m-d H:i:s");
            $mthModel->balance = $balance + $aResponse['fAmount'];
            $mthModel->particulars = "Deposit from ". $payment_processors_name;
            $mthModel->payment_processors_id = $payment_processors_id;
            $mthModel->save();
            
            // get super admin here from db by member type 3  
            // ADD TO Withdraw
            $superid = Member::model()->find("member_type=:member_type", array('member_type'=>  LevelLookUp::SUPERADMIN))->member_id;
            $sbalance = $this->getCurrentBalance($superid);
            
            $smthModel = new MemberTransactionHistory();
            $smthModel->member_id = $superid;
            $smthModel->credit = $aResponse['fAmount'];
            $smthModel->debit = 0;
            $smthModel->transaction_date = date("Y-m-d H:i:s");
            $smthModel->balance = $sbalance + $aResponse['fAmount'];
            $smthModel->particulars = "Deposit by ref_id from ". $payment_processors_name;
            $smthModel->payment_processors_id = $payment_processors_id;
            $smthModel->ref_id = Yii::app()->user->id;
            $smthModel->save();
            
            /**
             * $aResponse = array(
             * 	'sId'        => (string), //'TEST MODE' if test mode is enabled
             * 	'sDate'      => (string),
             *  'fAmount'    => (float) ,            
             *  'sCurrency'  => (string),
             *  'fFee'       => (float) , //Zero in test mode
             *  'sType'      => (string), //'TEST Store Received' in test mode
             *  'iTypeId'    => (string), //Zero in test mode
             *  'sEmail'     => (string),
             *  'sDetails'   => (string),
             *  'sStatus'    => (string), //'Completed' or 'TEST SUCCESS' in test mode
             * 	 // OPTIONAL
             *  'cf_1'	     => (string),
             *  'cf_2'	     => (string),
             *  'cf_3'	     => (string),
             *  'cf_4'	     => (string),
             *  'cf_5'	     => (string),
             *  'cf_6'	     => (string),
             *  'cf_7'	     => (string),
             *  'cf_8'	     => (string),
             * 
             * );
             * 
             * Note: To check if payment was not made in test mode and is completed, 
             * you have to make sure that sStatus equals to 'Completed'
             */
            //@todo: check if order amount and currency is valid
            //@todo: check your order status
        } catch (EgoPayException $e) {
            die($e->getMessage());
        }
        $model = array(
                'msg'=>"<p> We have received your payment. Your business is appreciated! </p>",
                'resget'=>$_GET,
                'respost'=>$_POST
        );

        $this->render('_deposit_success', array('model' => $model));
        }
        
        public function actionEpFail(){
            try {
            $oEgopay = new EgoPaySciCallback(array(
                'store_id' => '3MSB8NZP57J9',
                'store_password' => 'BH;qByO=hI^RZJ1FZ[UGM7aQ]HiXr:o9'
            ));
            $aResponse = $oEgopay->getResponse($_POST);
            
        } catch (EgoPayException $e) {
            die($e->getMessage());
        }
            
            $model = array(
                'msg'=>"<p>Payment has failed. Please contact with site administrator</p>",
                'resget'=>$_GET,
                'respost'=>$_POST
            );
            $this->render('_deposit_fail', array('model' => $model));
        }
        
        public function loadModel($id) {
		$model = MemberPosition::model()->findByPk($id);
		if ($model === null)
		throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}
        
        public function actionPositions () {
               $dataProvider = new CActiveDataProvider('MemberPosition', array(
                    'criteria' => array(
                        'condition' => 'member_id='.Yii::app()->user->id,
                        'order' => 'purchase_date DESC',
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                    ),
                ));
               //$model = MemberPosition::model();
                //$model = MemberPosition::model()->findAll('member_id=:member_id', array(':member_id'=>Yii::app()->user->id));
                $this->render('positions', array('dataProvider' => $dataProvider));
        }

	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'member-position-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

}
